import React, { useEffect, useState, useCallback, useRef, FC, useMemo, CSSProperties } from 'react';
import i18n from 'i18n-js';
import moment from 'moment';
import Taro from '@tarojs/taro';
import { observer } from 'mobx-react';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import { View, Text } from '@tarojs/components';
import FlexScrollView from '@/components/FlexScrollView';
import { GButton } from '@/components/GButton';
import { IProduct, getGroupProductWithID } from '@/config/product';
import homesModel from '@/models/homes';
import { deviceDefaultName } from '@/models/deviceList';
import languageModal from '@/models/language';
import { backToRouter } from '@/utils';

import { useDeviceListStore } from '@/hooks';
import { isSameDevice } from '@/utils';
import SDK from '@/utils/SDK';
import BleCheckTip from "@/container/BleCheckTip";
import BTWifiConfig from '../../models/configModel/BTWifiConfig';
import configWifiModel from '../../models/configWifi';
import { goToSuccess, goToFail, postBleConfigRes } from '../../models/configTool';
import Searching from '../../components/Searching';
import RadarTitle from '../../components/RadarTitle';
import ConfigDeviceItem, { ConfigStateEnum, IStateClick, configDeviceTime } from './ConfigDeviceItem';
import SearchingView from '../../components/SearchingView';

const btWifiIcon =
  'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/375869/media/btWifiIcon_1653299554549.png';

const BTWifiMaxHeight = 320;
const windowInfo = wx.getWindowInfo()

export interface IStateDevice extends IDevice {
  state: ConfigStateEnum;
}

const dstyles = GStyleSheet.create({
  container: {
    width: '100%',
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-start',
    overflow: 'hidden',
  },
  header: {
    width: '100%',
    paddingLeft: 40,
  },
  headerText: {
    color: DynamicColors.titleTextColor,
    fontSize: 18,
    fontWeight: 500,
  },
  findView: {
    width: '100%',
    justifyContent: 'flex-start',
    marginBottom: 20,
  },
  findIcon: {
    width: 25,
    height: 25,
    marginRight: 10,
  },
  list: {
    width: '100%',
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'flex-start',
    overflow: 'hidden',
    marginBottom: 10,
  },
});

const maxProgress = 100; // 最大进度是100
const congfigTime = 100; // 配网时间100s


interface IProps {
  productConfig?: IProduct;
  shortShow?: boolean;
  style?: CSSProperties;
}

const BTWifiConifg: FC<IProps> = ({ style, productConfig, shortShow = false }) => {
  const styles = dstyles.useDynamicStyle();
  const [progress, setProgress] = useState(0);
  const progressRef = useRef(progress);
  const showRef = useRef(true);

  useEffect(() => {
    showRef.current = true;
    return () => {
      BTWifiConfigRef.current && BTWifiConfigRef.current.endConfig();
      showRef.current = false;
    };
  }, []);

  const BTWifiConfigRef = useRef(new BTWifiConfig({ productConfig }));
  const pksRef = useRef(productConfig ? getGroupProductWithID(productConfig) : []);
  console.log('useBleConfigManager pks', pksRef.current);
  const { sdkBleDevices } = useDeviceListStore();
  console.log('sdkBleDevices', sdkBleDevices);
  const [bindRecordList, setBindRecordList] = useState<IStateDevice[]>([]);
  const bindingRef = useRef(false);
  const bindQueueRef = useRef<IStateDevice[]>([]);
  const bleDevicesRef = useRef<IStateDevice[]>([]);
  const canConifgBleDevices = useMemo(() => {
    let filterPKDevices = sdkBleDevices.filter(i => i.bleWorkStatus == 1 && !!i.productKey);
    if (BTWifiConfigRef.current.productConfig && !configWifiModel.notFilterPk) {
      if (pksRef.current) {
        filterPKDevices = filterPKDevices.filter(
          i => pksRef.current.findIndex(pConfig => pConfig.productKey == i.productKey) > -1
        );
      } else {
        filterPKDevices = filterPKDevices.filter(
          i => i.productKey === BTWifiConfigRef.current.productConfig.productKey
        );
      }
    }
    return filterPKDevices;
  }, [sdkBleDevices]);

  console.log('canConifgBleDevices', canConifgBleDevices);

  const list = useMemo(() => {
    // return data;
    let arr = bleDevicesRef.current;
    if (arr && arr.length > 0) {
      // 把ready状态的与canConifgBleDevices比较，不存在的就删掉
      arr = arr.filter(i => {
        if (i.state == ConfigStateEnum.ready) {
          return canConifgBleDevices.findIndex(bleDevice => isSameDevice(bleDevice, i)) > -1;
        }
        return true;
      });
    }
    bindRecordList?.forEach(bindDevice => {
      const index = arr.findIndex(i => isSameDevice(bindDevice, i));
      if (index > -1) {
        arr.splice(index, 1, { ...bindDevice });
      }
    });
    canConifgBleDevices?.forEach(d => {
      const index = arr.findIndex(i => isSameDevice(d, i));
      if (index < 0) {
        arr.push({ ...d, state: ConfigStateEnum.ready });
      }
    });
    bleDevicesRef.current = arr;
    return arr;
  }, [canConifgBleDevices, bindRecordList]);

  console.log('useBleConfigManager', list);

  const updateDeviceState = useCallback(
    (device: IStateDevice) => {
      const index = bindRecordList.findIndex(bindDevice => isSameDevice(bindDevice, device));
      if (index > -1) {
        bindRecordList.splice(index, 1, device);
      } else {
        bindRecordList.push(device);
      }
      setBindRecordList([...bindRecordList]);
    },
    [bindRecordList]
  );

  const configDeviceFunRef = useRef<(deivce: IStateDevice) => void>();

  const checkBindQueue = useCallback(() => {
    if (showRef.current) {
      if (bindQueueRef.current && bindQueueRef.current.length > 0) {
        const device = bindQueueRef.current.splice(0, 1);
        if (configDeviceFunRef.current) {
          configDeviceFunRef.current(device[0]);
        }
      } else {
        // 已经没有了
        // 如果全部添加失败，跳转到失败页面
        if (bindRecordList.length > 0 && bindRecordList.every(i => i.state == ConfigStateEnum.fail)) {
          goToFail(true);
        } else {
          backToRouter('pages/home/index');
        }
      }
    } else {
    }
  }, []);

  const configDevice = useCallback(
    async (device: IStateDevice) => {
      console.log(bindingRef.current);
      if (bindingRef.current) {
        // 如果绑定中，就把要绑定的设备放进绑定队列
        const index = bindQueueRef.current.findIndex(i => isSameDevice(i, device));
        if (index < 0) {
          bindQueueRef.current.push(device);
          updateDeviceState({ ...device, state: ConfigStateEnum.preLoading });
        }
        return {};
      }
      bindingRef.current = true;

      updateDeviceState({ ...device, state: ConfigStateEnum.loading });
      console.log('BTWifiConfigRef', BTWifiConfigRef.current);
      const startMoment = moment();
      const configRes = await BTWifiConfigRef.current.startConfig({
        wifiName: configWifiModel.wifiName,
        password: configWifiModel.password,
        softAPSSIDPrefix: device.name,
        timeout: configDeviceTime,
      });
      if (configRes.success && configRes.data && configRes.data.length > 0) {
        // 直接返回成功
        // backToRouter('pages/home/index');
        const cDevice = configRes.data[0];
        bindingRef.current = false;
        updateDeviceState({ ...cDevice, state: ConfigStateEnum.success });
        setTimeout(() => {
          checkBindQueue();
        }, 300);
        return;
       
        // const deviceName = deviceDefaultName(cDevice, languageModal);
        // const aepRes = await homesModel.addDevice({ device: { ...cDevice, name: deviceName } });
        // console.log('aep绑定结果', aepRes);
        // if (aepRes.success) {
        //   delete aepRes.data.mac;
        //   const aepDevice = { ...device, ...aepRes.data };
        //   bindingRef.current = false;
        //   // deviceListModal.getDeviceList();
        //   updateDeviceState({ ...aepDevice, state: ConfigStateEnum.success });
        //   setTimeout(() => {
        //     checkBindQueue();
        //   }, 300);
        //   // 配网埋点
        //   postBleConfigRes({ productKey: device.productKey, success: true, res: {}, startMoment });
        //   return;
        // } else {
        //   // 配网埋点
        //   postBleConfigRes({ productKey: device.productKey, success: false, res: aepRes, startMoment });
        // }
      } else {
        // 配网埋点
        postBleConfigRes({ productKey: device.productKey, success: false, res: configRes, startMoment });
      }

      bindingRef.current = false;
      updateDeviceState({ ...device, state: ConfigStateEnum.fail });
      checkBindQueue();
    },
    [updateDeviceState, checkBindQueue]
  );

  useEffect(() => {
    configDeviceFunRef.current = configDevice;
  }, [configDevice]);

  useEffect(() => {
    progressRef.current = progress;
  }, [progress]);

  useEffect(() => {
    SDK.startAutoScan();
  }, []);

  const timerRef = useRef<any>(null);

  const endTimer = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  const timerAdd = useCallback(() => {
    if (progressRef.current < maxProgress) {
      setProgress(progressRef.current + 1);
    } else {
      endTimer();
      goToFail();
    }
  }, [endTimer]);

  const startTimer = useCallback(() => {
    endTimer();
    timerRef.current = setInterval(timerAdd, (congfigTime / maxProgress) * 1000);
  }, [endTimer, timerAdd]);

  useEffect(() => {
    if (!shortShow) {
      startTimer();
    }
  }, []);

  useEffect(() => {
    if (list.length > 0) {
      endTimer();
    }
  }, [list, endTimer]);

  const deviceItemClick = useCallback(
    ({ device, state }: IStateClick) => {
      console.log('deviceItemClick', configWifiModel.wifiName, configWifiModel.password);
      if (!configWifiModel.wifiName || !configWifiModel.password) {
        Taro.navigateTo({
          url: '/pages/configDevice/selectWifi/index?isAddWifi=1',
          events: {
            'confirmEventKey': () => {
              if (state == ConfigStateEnum.ready) {
                configDevice({ ...device, state });
              }
            },
          },
        });
        return;
      }

      if (state == ConfigStateEnum.ready) {
        configDevice({ ...device, state });
      } else if (state == ConfigStateEnum.fail) {
        configDevice({ ...device, state });
      }
    },
    [configDevice]
  );

  const haveDevices = useMemo(() => {
    return list.length > 0;
  }, [list.length]);

  const show = useMemo(() => {
    if (shortShow) {
      return true;
    }
    return haveDevices;
  }, [shortShow, haveDevices]);

  const onConfirm = useCallback(() => {
    const successDevices = bindRecordList.filter(i => i.state == ConfigStateEnum.success);
    if (successDevices && successDevices.length > 0) {
      successDevices.forEach(i => configWifiModel.addDevice(i));
      goToSuccess();
    } else {
      goToFail();
    }
  }, [bindRecordList]);

  const cannotNext = useMemo(() => {
    const index = bindRecordList.findIndex(
      i => i.state == ConfigStateEnum.loading || i.state == ConfigStateEnum.preLoading
    );
    return index > -1;
  }, [bindRecordList]);

  const listStyle = useMemo(() => {
    const height = Math.min(100 + list.length * 60, BTWifiMaxHeight);
    return shortShow && haveDevices ? { maxHeight: BTWifiMaxHeight, height } : {};
  }, [shortShow, haveDevices, list]);

  const deviceListDom = list.map(device => {
    return (
      <ConfigDeviceItem
        key={device.mac + device.productKey}
        device={device}
        state={device.state}
        onStateClick={deviceItemClick}
      />
    );
  });


  const content = useMemo(() => {
    return show ? (
      <View className='centerFlex' style={styles.list}>
        <View style={styles.header}>
          {haveDevices && (
            <>
              <RadarTitle />
              <Text style={styles.headerText}>{i18n.t('FOND_DEVICE', { num: list.length })}</Text>
            </>
          )}
        </View>
        {haveDevices && (
          <FlexScrollView id='BleDevceList' scrollStyle={{ ...listStyle, paddingLeft: 20, paddingRight: 20 }}>
            {deviceListDom}
          </FlexScrollView>
        )}
        {!haveDevices && shortShow && <SearchingView />}
      </View>
    ) : (
      <View className='centerFlex' style={{ flex: 1 }}>
        <Searching progress={progress} icon={btWifiIcon} />
      </View>
    )
  }, [progress, deviceListDom, haveDevices, show, shortShow, listStyle, styles, list.length])

  return (
    <>
      <View style={{ ...styles.container, ...style }} className='centerFlex BTWifiConfig'>
        <View style={{ flex: 1, display: 'flex', flexDirection: 'column', width: "100%", }}>
          {shortShow ? <BleCheckTip>
            {content}
          </BleCheckTip> : content}
        </View>
        {show && !shortShow && <GButton text={i18n.t('NEXT')} onPress={onConfirm} disabled={cannotNext} />}
      </View>
    </>
  );
};

export default observer(BTWifiConifg);
